<?php
  /**
  * 系统公用函数
  */

  /**
  * P()打印函数
  */
  function p($data)
  {
   echo "<pre>";
   print_r($data);
   echo "</pre>";
  }


//调用钩子函数
function hook($hook,$params=null){
    \Think\Hook::listen($hook,$params);        //监听一个钩子
 }

  
//匹配图片
function get_img($str){
    $str = stripslashes($str);
    $pattern = "/<[img|IMG][^>]*(src|SRC)\=[\"|'| ]((http:\/\/[^>]*)(jpg|gif|png|bmp|jpeg))[\"|'| ]/i";   //获取所有图片标签的全部信息

    preg_match_all($pattern, $str, $matches);

    return $matches[2]; 
}



//下载远程图片
function get_photo($url,$filename='',$savefile= 'uploads/images/') 
{   
    $imgArr = array('gif','bmp','png','ico','jpg','jepg');
    if(!$url) return false;
    if(!$filename) {   
      $ext=strtolower(end(explode('.',$url)));   
      if(!in_array($ext,$imgArr)) return false;
      $filename= time() . mt_rand(1000,9999).'.'.$ext;   
  }
  $savefile ='uploads/images/'.date('Y-m').'/';
  if(!is_dir(FCPATH.$savefile)) mkdir($savefile, 0777);
  if(!is_readable(FCPATH.$savefile)) chmod($savefile, 0777);
  $filename =  $savefile.$filename;
  ob_start();   
  readfile($url);   
  $img = ob_get_contents();   
  ob_end_clean();   
  $size = strlen($img);   
  $fp2=@fopen($filename, "a");   
  @fwrite($fp2,$img);   
  @fclose($fp2);
  //$filename = $savefile.$filename;
  return $filename;  
}   

  
  //判断文章的id
  
  function get_content_id($data1=null,$data2=null){
      if(!empty($data2)){ 
        return $data2; 
      }else{ 
        return $data1['id'];
      }
  }

 //百分比
 function baifenbi($p,$t){
  return sprintf('%.2f%%',$p/$t*100);
 }

 
 /**
  * [tip description]
  * $type 提示类型
  * $msg 提示语句
  * @return
  */
 function tip($type=null,$msg=null,$ajax,$ajaxdata=null){
    if(empty($ajax)){ 
      $Think->$type($msg);
    }else{
      $this->ajaxReturn($ajax);
    }
  }
 
 /**
  * [en_crypt 对称加密函数]
  * @param  [type] $str [要加密的字符串]
  * @param  [type] $key [加密钥匙]
  * @return [type] str  [description]
  */
 function en_crypt($str,$key=null){ 
    $crypt = new \Think\Crypt\Driver\Think();
    if(!$key){ 
      $key=C("YZ_USER_KEY");
    }
    return $crypt->encrypt($str,$key);
 }

 /**
  * [en_crypt 对称解密函数]
  * @param  [type] $str [要加密的字符串]
  * @param  [type] $key [加密钥匙]
  * @return [type] str  [description]
  */
 function de_crypt($str,$key=null){ 
    $crypt = new \Think\Crypt\Driver\Think();
    if(!$key){ 
      $key=C("YZ_USER_KEY");
    }
    return $crypt->decrypt($str,$key);
 }

/**
 * [xml_to_array description]
 * @param  [type] $xml [description]
 * @return [type]      [description]
 */
function xml_to_array( $xml )
{
    $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches))
    {
        $count = count($matches[0]);
        $arr = array();
        for($i = 0; $i < $count; $i++)
        {
            $key= $matches[1][$i];
            $val = xml_to_array( $matches[2][$i] );  // 递归
            if(array_key_exists($key, $arr))
            {
                if(is_array($arr[$key]))
                {
                    if(!array_key_exists(0,$arr[$key]))
                    {
                        $arr[$key] = array($arr[$key]);
                    }
                }else{
                    $arr[$key] = array($arr[$key]);
                }
                $arr[$key][] = $val;
            }else{
                $arr[$key] = $val;
            }
        }
        return $arr;
    }else{
        return $xml;
    }
}

 
  //列表URL生成
  function list_url($data)
  {  
     $uid=session("user.id");
     if($uid){ 
       $uid= "/".$uid;
     }
     return U("/Article/index".$uid)."?cid=".$data['id'];
  } 


  //内容页生成
  function show_url($data)
  {
    $uid=session("user.id");
    if($uid){ 
       $uid= "/".$uid;
    }
    return U("/Article/show/".$data['id'],'','',$data['yumi_url']).$uid;
  }

 
 //CURL
  function get_url($url)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://".$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    $output = curl_exec($ch);
    curl_close($ch);
    p($output);DIE();
    return $output;
  }

//获取真实IP
function get_ip() {
        $clientip = '';
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $clientip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $clientip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $clientip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $clientip = $_SERVER['REMOTE_ADDR'];
        }

        preg_match("/[\d\.]{7,15}/", $clientip, $clientipmatches);
        $clientip = $clientipmatches[0] ? $clientipmatches[0] : 'unknown';
        return $clientip;
    }


    /**
     * 检查IP是否在指定的网络范围内
     * 
     * 1. 网络范围表示方法：
     *      通配符:      1.2.3.*
     *      CIDR值:     1.2.3.0/24 或 1.2.3.4/255.255.255.0
     *      IP段:       1.2.3.0-1.2.3.255
     * 2. 仅支持IPv4。
     * 3. 考虑到目前实用性不高，而且随着PHP本身的发展，将来或许会有更好的解决方案，
     *    暂时先不发布支持IPv6的版本，有兴趣的同学可联系我进一步交流或者自行研究。
     * 4. 实现IPv6的支持，需要至少32位无符号整数进行位运算，而PHP只支持32位有符号整数，
     *    可以使用float类型突破这个限制，但float类型不支持位运算，这是需要解决的首要问题。
     * @param  string  $ip    IP地址
     * @param  string  $range 网络范围
     * @return boolean
     */
   function ip_in_range($ip, $range) {
        if (strpos($range, '/') !== false) {
            // CIDR值
            list($range, $netmask) = explode('/', $range, 2);
            if (strpos($netmask, '.') !== false) {
                $netmask = str_replace('*', '0', $netmask);
                $netmask_dec = ip2long($netmask);
                return ((ip2long($ip) & $netmask_dec) === (ip2long($range) & $netmask_dec));
            } else {
                $x = explode('.', $range);
                while (count($x) < 4) {
                    $x[] = '0';
                }
                list($a, $b, $c, $d) = $x;
                $range = sprintf('%u.%u.%u.%u', empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c, empty($d) ? '0' : $d);
                $range_dec = ip2long($range);
                $ip_dec = ip2long($ip);

                $wildcard_dec = pow(2, (32 - $netmask)) - 1;
                $netmask_dec = ~ $wildcard_dec;

                return (($ip_dec & $netmask_dec) === ($range_dec & $netmask_dec));
            }
        } else {
            // 通配符格式，转换为IP段进行判断
            if (strpos($range, '*') !== false) {
                $lower = str_replace('*', '0', $range);
                $upper = str_replace('*', '255', $range);
                $range = "{$lower}-{$upper}";
            }

            // IP段
            if (strpos($range, '-') !== false) {
                list($lower, $upper) = explode('-', $range, 2);
                $lower_dec = (float) sprintf('%u', ip2long($lower));
                $upper_dec = (float) sprintf('%u', ip2long($upper));
                $ip_dec = (float) sprintf('%u', ip2long($ip));
                return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
            }

            // 网络范围格式不正确，返回false
            return false;
        }
    }


     //判断是不是手机访问
     function is_phome()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT']; 
        $mobile_agents = array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi", 
        "android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio", 
        "au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu", 
        "cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ", 
        "fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi", 
        "htc","huawei","hutchison","inno","ipad","ipaq","iphone","ipod","jbrowser","kddi", 
        "kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo", 
        "mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-", 
        "moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia", 
        "nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-", 
        "playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo", 
        "samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank", 
        "sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit", 
        "tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin", 
        "vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce", 
        "wireless","xda","xde","zte"); 
        $is_mobile = false; 
        foreach ($mobile_agents as $device) { 
            if (stristr($user_agent, $device)) { 
                $is_mobile = true; 
                break; 
            } 
        } 
        return $is_mobile;
    }
    

    //获取系统浏览器平台图标
     function str_img($str)
     {
        $str= explode(' ', $str);
        $exe=".png";
        return "/Useragent/img/16/".$str[0].$exe;
     }

     //判断是否为合法IP地址
     function is_ip($ip){
      if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip))
      {
       return 1;
        }else{
        return 0;
      }
}

     //ip2long函数负数BUG
     function iplong($ip){ 
       return bindec(decbin(ip2long($ip)));
     }

   
    /** 
     * 记录错误信息 
     */  
    function YZLOG($msg) {  
      $params = func_get_args();  
      $traces = debug_backtrace();  
      $trace = array_pop($traces);  
      sysrecord($msg, $trace, 'error');  
    }  
      

    /** 
     * 写文件 
     * @ignore 
     */  
    function sysfile($filename, $msg, $mode = null) {  
      $path = dirname($filename);  
      if (!file_exists($path)) {  
        mkdir($path, 0666, true);  
      }  
      $flag = LOCK_EX;  
      if ($mode) {  
        switch ($mode) {  
          case "add":  
            $flag = FILE_APPEND | LOCK_EX;  
            break;  
          case "a":  
            $flag = FILE_APPEND | LOCK_EX;  
            break;  
          default:  
            break;  
        }  
      }  
      file_put_contents($filename, $msg, $flag);  
    }  


    /** 
    * 记录信息 
    * @ignore 
    */  
    function sysrecord($params, $trace, $level) {  
    $path = APP_PATH. "/YZLOG/";  
    //TODO 日志保存目录最好修改一下  
    $file = $trace['file'];  
    $filename = $path . "$level/" . date("Y-m-d") . '.log';  
    $msg = "[" . date("m-d H:i:s") . "] " . $params . "\r\n";
    sysfile($filename, $msg, 'add');  
    }

    
    //获取阿拉伯数字对应的中文
    function get_num_cn($num)
    { 
     $array =array(0=>'零',1=>"一",2=>"二",3=>"三",4=>"四",5=>'五', 6=>"六",7=>"七",8=>'八',9=>'九',10=>'十');
     if(isset($array[$num])){
        return $array[$num];
       }else{
        return false;
       }
    }
    

    //计算数组值有一个不为真值返回为假
    function is_array_true($arr)
    {  
       $code = true; 
       if(is_array($arr)){
       foreach ($arr as $v) {
           if(!$v)
           {
             $code = false; 
            continue;
           }
        }
      }
      return $code;
    }

   
   //计算单条加款日志要付出的总额
   function zonger($v)
   {
      $price = $v['price'];
      if(!empty($v['jiakuan_xiaji_log'])){
          foreach ($v['jiakuan_xiaji_log'] as  $v2) {
                $price =  $price+ $v2['price'];
            }  
      }
      return $price;
   }
   

   //保留2位小数并且不四舍五入
   function get_erwei($num)
   {
     return floor($num*100)/100;
   }

   
   //获取提现类型
   function get_type($type){
     if($type==1){
       return "支付宝";
     }else if($type = 2){
        return "话费充值";
     }else{
        return "未知";
     }
   }

   
   //获取提现状态
   function get_status($status)
   { 
     switch ($status) {
       case 1:
         $code = '等待处理';
         break;
        case 2:
         $code = '提现失败';
        break;
        case 3:
         $code = '拒绝提现';
        break;
         case 4:
         $code = '提现成功';
        break;    
       default:
         $code = '未知错误';
         break;
     }
     return $code;

   }
   

/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
function F2($name, $value='', $path=DATA_PATH) {
    static $_cache  = array();
    $filename       = $path . $name . '.php';
    if ('' !== $value) {
        if (is_null($value)) {
            // 删除缓存
            return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename);
        } else {
            // 缓存数据
            $dir            =   dirname($filename);
            // 目录不存在则创建
            if (!is_dir($dir))
                mkdir($dir,0755,true);
            $_cache[$name]  =   $value;
            return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
        }
    }
    if (isset($_cache[$name]))
        return $_cache[$name];
    // 获取缓存数据
    if (is_file($filename)) {
        $value          =   include $filename;
        $_cache[$name]  =   $value;
    } else {
        $value          =   false;
    }
    return $value;
}


//获取IP地址城市
 function get_cs($ip)
 {
      $Ip = new \Org\Net\IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
      $area = $Ip->getlocation($ip); // 获取某个IP地址所在的位置
      return  iconv("gb2312","utf-8",$area['country']);
 }


 function shou($url)
 {
  if(strpos($_SERVER['REQUEST_URI'],"Article")!==false and strpos($_SERVER['REQUEST_URI'],"So")!==false){
    $url=unicode_decode($url);
    if($url!==$_SERVER['HTTP_HOST']){
      $tig= "\u8fd9\u4e0d\u4e00\u4e2a\u514d\u8d39\u7a0b\u5e8f\u002c\u4f60\u771f\u5728\u4f7f\u7528\u76d7\u7248\u7a0b\u5e8f\u002c\u8d2d\u4e70\u5546\u4e1a\u6388\u6743\u8bf7\u8054\u7cfb\u0071\u0071\u003a\u0037\u0038\u0031\u0033\u0031\u0038\u0030\u002e\u5012\u5356\u8d29\u5356\u5fc5\u5c06\u7684\u53d7\u5230\u672c\u516c\u53f8\u8d77\u8bc9\u0021";
      die(unicode_decode($tig));
    }
   }
 }

function shou2($code){
   $url1=strpos($_SERVER['REQUEST_URI'],"Article");
   $url2=strpos($_SERVER['REQUEST_URI'],"So");
   $url3=strpos($_SERVER['REQUEST_URI'],"Api");
   $url4=strpos($_SERVER['REQUEST_URI'],"buy");
   if($url1 || $url2 ||$url3 || $url4){
   }else{
	     $key= "\u0043\u0048\u0045\u004e\u0059\u0055\u0048\u0041\u004e\u0035\u0032\u0030";
       $url=$_SERVER['HTTP_HOST'].unicode_decode($key);
	     $code2=md5($url);
       $code2=base64_encode($code2);
       if($_SERVER['HTTP_HOST']!=="www.ev9.cn"){
       if($code2!==$code){
          $tig= "\u8fd9\u4e0d\u4e00\u4e2a\u514d\u8d39\u7a0b\u5e8f\u002c\u4f60\u771f\u5728\u4f7f\u7528\u76d7\u7248\u7a0b\u5e8f\u002c\u8d2d\u4e70\u5546\u4e1a\u6388\u6743\u8bf7\u8054\u7cfb\u0071\u0071\u003a\u0037\u0038\u0031\u0033\u0031\u0038\u0030\u002e\u5012\u5356\u8d29\u5356\u5fc5\u5c06\u7684\u53d7\u5230\u672c\u516c\u53f8\u8d77\u8bc9\u0021";
          header("Content-type: text/html; charset=utf-8");
          die(unicode_decode($tig));
         }
       }
      }
}
//shou2(SYSTEM_SQM);
function unicode_decode($name)
  {
    // 转换编码，将Unicode编码转换成可以浏览的utf-8编码
    $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
    preg_match_all($pattern, $name, $matches);
    if (!empty($matches))
    {
        $name = '';
        for ($j = 0; $j < count($matches[0]); $j++)
        {
            $str = $matches[0][$j];
            if (strpos($str, '\\u') === 0)
            {
                $code = base_convert(substr($str, 2, 2), 16, 10);
                $code2 = base_convert(substr($str, 4), 16, 10);
                $c = chr($code).chr($code2);
                $c = iconv('UCS-2', 'UTF-8', $c);
                $name .= $c;
            }
            else
            {
                $name .= $str;
            }
        }
    }
    return $name;
}

  function adtype($data)
   {
      if($data['type']==1){
         return "文字广告";
      }else if($data['type']==2){
         return "图片广告";
      }else{
         return "JS广告";
      }
   }

 function adpos($data){
      if($data['pos']==1){
         return "顶部广告";
      }else if($data['pos']==2){
         return "顶部广告";
      }else{
         return "最底部广告";
      }
 }

 function getad($pos)
 {
  $data= M("ad")->where("pos=".$pos)->order("sort desc")->select();
  return $data;
 }


 //清空项目的缓存
function clearCache()
{
    import("Lib.Dir", APP_PATH);
    if (is_dir(APP_PATH."Runtime")){
        Dir::delDir(APP_PATH."Runtime");
    }

    if(is_dir(APP_PATH."html")){
        Dir::delDir(APP_PATH."html");
    }
}


function is_get_url()
    {   
        $get_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $site_url = C("SITE_URL");
        if(strpos($get_url,$site_url)){
           return false;
        }else{
           return true; //如果不等于初始判断通过
        }
    } 



//订单状态
function order_type($type)
{
   switch ($type) {
     case 1:
       $msg="等待处理";
       break;
     case 2:
       $msg="已电话确认,等待发货.";
       break;
      case 3:
       $msg="已发货";
       break;
      case 4:
       $msg="已签收";
       break;
      case 5:
       $msg="拒收";
       break;
       case 6:
       $msg="申请退货";
       break;
       case 7:
       $msg="无效订单";
       break;
       case 9:
       $msg="等待确定";
       break;
       break;
     default:
       # code...
       break;
   }
   return $msg;
}


//
function price_array($arr)
{ 
  $a='';
  foreach ($arr as$key=>$v) {
     $a[$key]=$v['price'];
  }
  return $a;
}

/////
function ticheng_array($arr)
{
   $a='';
   foreach ($arr as $key => $v) {
     $a[$key]=$v['ticheng'];
   }
   return $a;
}



?>